//
//  MyScrollView.m
//  PhotoBrowserEx
//
//  Created by on 10-6-12.
//  Copyright 2010 重庆奥芬多网络科技有限公司. All rights reserved.
//

#import "MyScrollView.h"



@implementation MyScrollView


@synthesize originFrame;


#pragma mark -
#pragma mark === Intilization ===
#pragma mark -
- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
    {
        self.delegate = self;
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        //        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
        self.backgroundColor = [UIColor whiteColor];
        self.imageView  = [[UIImageView alloc] initWithFrame:self.bounds];
        self.imageView.autoresizesSubviews = NO;
        //		self.imageView.contentMode = UIViewContentModeScaleToFill;

        [self addSubview:self.imageView];
        [self.imageView setUserInteractionEnabled:YES];
        UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                           action:@selector(handleDoubleTap:)];
        [doubleTapGesture setNumberOfTapsRequired:2];
        [self.imageView addGestureRecognizer:doubleTapGesture];

        //从不设置会导致，zoomToRect行为怪异
        [self setMinimumZoomScale:1];
        [self setMaximumZoomScale:5];

        //缩放到最小或最大，回弹动画
        //        self.bouncesZoom = NO;
    }
    return self;
}

#pragma Actions
- (void)resizeImageView
{
    UIImage *image = self.imageView.image;
    if (!image) {
        return;
    }
    //    float zoomScale = self.zoomScale;
    [self setMinimumZoomScale:kScreenHeight/image.size.height];
    [self setMaximumZoomScale:fmax(self.minimumZoomScale*5, 5)];
    //必须调节imageview大小为设定的zoomScale，否则切换后的zoomScale默认为当前图片的frame，导致缩放不符合
    self.zoomScale = MIN(MAX(self.minimumZoomScale, self.zoomScale), self.maximumZoomScale);
    if (self.zoomScale == 1.0) {
        self.zoomScale = self.minimumZoomScale;
    }
    [self.imageView setFrame:CGRectMake(0, 0, image.size.width*self.zoomScale, image.size.height*self.zoomScale)];
    self.contentSize = self.imageView.frame.size;
}
- (void)resizeImageView:(CGSize)size
{
    [self setMinimumZoomScale:kScreenHeight/size.height];
    [self setMaximumZoomScale:fmax(self.minimumZoomScale*5, 5)];
    //必须调节imageview大小为设定的zoomScale，否则切换后的zoomScale默认为当前图片的frame，导致缩放不符合
    self.zoomScale = MIN(MAX(self.minimumZoomScale, self.zoomScale), self.maximumZoomScale);
    if (self.zoomScale == 1.0) {
        self.zoomScale = self.minimumZoomScale;
    }
    [self.imageView setFrame:CGRectMake(0, 0, size.width*self.zoomScale, size.height*self.zoomScale)];
    self.contentSize = self.imageView.frame.size;
}
- (void)removeSelf
{
    self.zoomScale = 1.0;
    [UIView animateWithDuration:0.5 animations:^{
        [self.imageView setFrame:self.originFrame];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark -
#pragma mark === UIScrollView Delegate ===
#pragma mark -
- (void)MyScrollViewDidZoom:(id)xx{
    //nothing.
}
//实现图片在缩放过程中居中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    if ([self.superview.nextResponder respondsToSelector:@selector(MyScrollViewDidZoom:)]) {
        [self.superview.nextResponder performSelector:@selector(MyScrollViewDidZoom:) withObject:self];
    }
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?(scrollView.bounds.size.width - scrollView.contentSize.width)/2 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?(scrollView.bounds.size.height - scrollView.contentSize.height)/2 : 0.0;
    CGPoint pt = CGPointMake(scrollView.contentSize.width/2 + offsetX,scrollView.contentSize.height/2 + offsetY);
    self.imageView.center = pt;

}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;

}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    [scrollView setZoomScale:scale animated:NO];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([self.superview.nextResponder respondsToSelector:@selector(scrollViewDidScroll:)]) {
        [self.superview.nextResponder performSelector:@selector(scrollViewDidScroll:) withObject:self];
    }
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
- (void)setContentOffset:(CGPoint)contentOffset
{
    //很奇怪，设置zoomToRect为minimumZoomScale，contentSize总会乱跑
    //    if (self.zoomScale-self.minimumZoomScale<0.01) {
    //        [super setContentOffset:CGPointZero];
    //    }else
    [super setContentOffset:contentOffset];
}
#pragma mark -
#pragma mark === UITouch Delegate ===
#pragma mark -
- (void)imageButtonClicked:(id)sender {
    //none use,just avoid warning..
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    //DLog(@"%s", _cmd);
    [[[UIApplication sharedApplication] windows][0] endEditing:YES];
    UITouch *touch = [touches anyObject];
    if ([touch tapCount] == 1){
        CGPoint point = [touch locationInView:self.imageView];
        if ([self.superview.nextResponder respondsToSelector:@selector(imageButtonClicked:)]) {
            [self.superview.nextResponder performSelector:@selector(imageButtonClicked:) withObject:NSStringFromCGPoint(point) afterDelay:.3];
        }else{
            //[self performSelector:@selector(removeSelf) withObject:nil afterDelay:0.5];
        }
    }
}
- (void)handleDoubleTap:(UIGestureRecognizer *)gesture
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [NSObject cancelPreviousPerformRequestsWithTarget:self.superview.nextResponder];
    float newScale = (self.zoomScale==self.minimumZoomScale)?self.maximumZoomScale:self.minimumZoomScale;
    [self zoomToRect:[self zoomRectForScale:newScale withCenter:[gesture locationInView:gesture.view]] animated:YES];
}

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
    CGRect zoomRect;
    zoomRect.size.height = self.frame.size.height / scale;
    zoomRect.size.width  = self.frame.size.width  / scale;
    zoomRect.origin.x = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
    return zoomRect;
}
#pragma mark -
#pragma mark === dealloc ===
#pragma mark -
//- (void)dealloc
//{
//    [saveButton release];
//	[image release];
//	[imageView release];
//	
//    [super dealloc];
//}

@end
